﻿using Microsoft.AspNetCore.Mvc;
using RuoVea.DynamicWebApi;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExSugar;
using RuoVea.ExSugar.Entity;
using RuoVea.ExUtil;
using RuoVea.OmiApi.Article.Entitys;
using RuoVea.OmiApi.Article.Service.Dto;
using SqlSugar;
using exDtoi18n = RuoVea.ExDto.Language.i18n;

namespace RuoVea.OmiApi.Article.Service;

/// <summary>
/// 点赞管理 🔷
/// </summary>
[ApiExplorerSettings(GroupName = "art")]
public class LikeService : IApplicationService
{
    private readonly SugarRepository<ArtLike> _thisRepository;
    private readonly ISqlSugarClient _sqlSugarClient;

    /// <summary>
    /// 点赞管理
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="sqlSugarClient"></param>
    public LikeService(SugarRepository<ArtLike> thisRepository, ISqlSugarClient sqlSugarClient)
    {
        _thisRepository = thisRepository;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 查询所有/分页🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<PageResult<ArtLike>> GetPagesAsync([FromQuery] LikeParam data)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(u => u.Article)
            .WhereIF(data.UserId > 0, u => u.Creator == data.UserId)
            .OrderByDescending(u => u.CreateTime)
            .ToPageAsync(data.PageNo, data.PageSize);
        return query;
    }

    /// <summary>
    /// 查询文章被点赞的次数
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<int> GetConntAsync([FromQuery] LikeDto data)
    {
        var query = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == data.ArticleId).CountAsync();
        return query;
    }

    /// <summary>
    /// 检查用户是否点赞了某篇文章
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<bool> GetIsLikeAsync([FromQuery] LikeDto data)
    {
        var query = await _thisRepository.AsQueryable()
            .Where(u => u.Creator == data.ArticleId && u.ArticleId == data.ArticleId).AnyAsync();
        return query;
    }

    /// <summary>
    /// 添加🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public virtual async Task<bool> AddDataAsync([FromBody] ArtLike data)
    {
        var isExist = await _thisRepository.IsAnyAsync(u => u.ArticleId == data.ArticleId && u.Creator == data.Creator);
        if (isExist) throw new ArgumentException(ErrorEnum.D9000.GetDescription(exDtoi18n.ResourceManager));

        var result = await _sqlSugarClient.Ado.UseTranAsync(async () =>
        {
            // 点赞数+1
            await _sqlSugarClient.Updateable<ArtArticle>()
                   .SetColumns(a => a.LikeCount == a.LikeCount + 1)
                   .Where(a => a.Id == data.ArticleId)
                   .ExecuteCommandAsync();
            return await _thisRepository.InsertAsync(data);
        });

        if (!result.IsSuccess)
            throw new Exception(exDtoi18n.failed + result.ErrorMessage);

        return result.IsSuccess;
    }

    /// <summary>
    /// 删除🔹
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete]
    public virtual async Task DeleteDataAsync([FromBody] EntityBaseId data)
    {
        data.Check();

        var dictType = await _thisRepository.GetFirstAsync(u => u.Id == data.Id);
        if (dictType == null) throw new ArgumentException(ErrorEnum.D1002.GetDescription(exDtoi18n.ResourceManager));

        if (dictType.IsDelete == IsDelete.Y)
            await _thisRepository.DeleteByIdAsync(data.Id);
        else
        {
            dictType.IsDelete = IsDelete.Y;
            // 点赞数-1
            await _sqlSugarClient.Updateable<ArtArticle>()
               .SetColumns(a => a.LikeCount == a.LikeCount - 1)
               .Where(a => a.Id == dictType.ArticleId && a.LikeCount > 0)
               .ExecuteCommandAsync();

            await _thisRepository.UpdateAsync(dictType);
        }
    }
}
